package com.zmx.b2c.order.messaging.queue;

import com.zmx.common.common.contents.MqQueueContents;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 超时未支付订单队列
 * @ClassName: TimeOutOrderQueue
 * @Author zhaomxr
 * @Date 2021-10-22 14:33
 */
@Configuration
public class TimeOutOrderQueue {

    /**
     * 未支付订单超时时间
     */
    @Value("${order.nopay.timeout}")
    private int orderNopayTimeout;

    /**
     * 订单超时未支付队列
     * @return
     */
    @Bean
    public Queue orderTimeOutQueue() {
        Map<String, Object> arguments = new HashMap<String, Object>(3);
        // 消息的生存时间 1分钟=30秒
        arguments.put("x-message-ttl", orderNopayTimeout);
        // 设置该队列所关联的死信交换器（当队列消息到期后依然没有消费，则加入死信 队列）
        arguments.put("x-dead-letter-exchange", MqQueueContents.ORDER_TIMEOUT_DLX_QUEUE);
        // 设置该队列所关联的死信交换器的routingKey，如果没有特殊指定，使用原队列的routingKey
        arguments.put("x-dead-letter-routing-key", MqQueueContents.ORDER_TIMEOUT_NOPAY_KEY);

        return new Queue(MqQueueContents.ORDER_TIMEOUT_QUEUE, true, false, false, arguments);
    }

    @Bean
    public Exchange orderTimeOutExchange() {
        return new DirectExchange(MqQueueContents.ORDER_TIMEOUT_QUEUE, true, false, null);
    }

    @Bean
    public Binding orderTimeOutRouting() {
        return BindingBuilder.bind(orderTimeOutQueue()).to(orderTimeOutExchange()).with(MqQueueContents.ORDER_TIMEOUT_NOPAY_KEY).noargs();
    }

    /**
     * 订单超时未支付死信队列
     * @return
     */
    @Bean
    public Queue orderTimeOutDlxQueue() {
        return new Queue(MqQueueContents.ORDER_TIMEOUT_DLX_QUEUE);
    }

    /**
     * 订单超时未支付死信交换器
     * @return
     */
    @Bean
    public Exchange orderTimeOutDlxExchange() {
        return new DirectExchange(MqQueueContents.ORDER_TIMEOUT_DLX_QUEUE, true, false, null);
    }

    /**
     * 订单超时未支付路由 | 指定匹配key为nopay未支付订单
     * @return
     */
    @Bean
    public Binding orderTimeOutDlxDlxRouting() {
        return BindingBuilder.bind(orderTimeOutDlxQueue()).to(orderTimeOutDlxExchange()).with(MqQueueContents.ORDER_TIMEOUT_NOPAY_KEY).noargs();
    }
}
